package com.ja10.books;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import com.example.books.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.widget.Toast;

public class ReserveDeleteActivity extends Activity {
	
	SimpleDatabaseHelper helper = null;
	SQLiteDatabase db = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_reserve_delete);
		
		AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
		
        // アラートダイアログのメッセージを設定します
        alertDialogBuilder.setMessage("選択された予約を取消してよろしいでしょうか？");
        
        alertDialogBuilder.setPositiveButton("キャンセル",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                });
        alertDialogBuilder.setNegativeButton("予約取消",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    	reserveDelete();
                    }
                });
        alertDialogBuilder.setCancelable(true);
        AlertDialog alertDialog = alertDialogBuilder.create();
        alertDialog.show();
	}

	public void reserveDelete() {
		// ヘルパーを準備
		helper = new SimpleDatabaseHelper(this);
		
		// 端末データベースの取得
		db = helper.getReadableDatabase();
		db.beginTransaction();
		String[] delId = { };
		int sqliteResult = db.delete("reserves", "id = ?", delId);
		
		String memberId = "";
		String bookIsbn = "";
		
		// 予約情報を取得するSQL文の用意
		String sql = "select r.id, user_id, book_isbn from members as m, reserves as r" +
						"where m.id = r.member_id and user_id = '" + memberId + "' and book_isbn = '" + bookIsbn + "'";

		Connection con = null;
		Statement smt = null;
		
		int mysqlResult = 0;
		
		try {
			con = DBManager.getConnection();
			smt = con.createStatement();
			ResultSet rs = smt.executeQuery(sql);
			
			if(rs.first() && sqliteResult > 0) {
				
				int id = rs.getInt(1);
				sql = "delete from reserves where id = " + id;
				mysqlResult = smt.executeUpdate(sql);
			}
			
			if(mysqlResult > 0) {
				db.setTransactionSuccessful();
				Toast.makeText(this, "予約を1件取消しました", Toast.LENGTH_SHORT).show();
			} else {
				Toast.makeText(this, "エラー", Toast.LENGTH_SHORT).show();
			}
		} catch(SQLException e) {
			e.printStackTrace();
		} finally {
			if(smt != null) {
				try {
					smt.close();
				} catch(SQLException ignore) {
					// none
				}
			}
			if(con != null) {
				try {
					con.close();
				} catch(SQLException ignore) {
					// none
				}
			}
			db.endTransaction();
			finish();
		}

	}

}
